import {defineStore} from 'pinia'
import {ref} from 'vue'
import {getMenuList} from '@/api/menu'
import type {MenuItem} from '@/api/types/menu'
import router from '@/router'
import Layout from '@/layout/index.vue'
import type {RouteComponent} from 'vue-router'

export interface GeneratedMenu {
    path: string
    title: string
    icon: string
    children: GeneratedMenu[]
}

interface RouteItem {
    path: string
    name: string
    component: RouteComponent | (() => Promise<RouteComponent>)
    meta: {
        title: string
    }
    children?: RouteItem[]
}

// 图标映射表
const ICON_MAP: Record<string, string> = {
    '/home': 'HomeFilled',
    '/roleManage': 'Setting',
    '/departmentManage': 'OfficeBuilding',
    '/menuManage': 'Menu',
    '/userManage': 'User',
    '/permissionManage': 'Key',
    '/accountManage': 'Wallet',
    '/employeeManage': 'UserFilled',
    '/storeManage': 'Histogram',
    '/performanceManage': 'Discount',
    '/vacation': 'Calendar',
    '/rules': 'SetUp',
    '/balance': 'Tickets',
    '/shiftManage': 'Operation',
    '/attendanceManage': 'MessageBox',
    '/attendance': 'Clock',
    '/schedulingManage': 'Clock',
    '/allocationManagement': 'Histogram',
    '/approvalManagement': 'MessageBox',
    '/SchedulingApprovals': 'Compass',
    '/Approval': 'Grid',
    '/salary':'Reading',
    '/salary-group':'Checked',
    '/FullTimePayroll':'Collection',
    '/calendar':'Calendar',
    '/ShiftsLabel':'FolderRemove',
    '/payment-full-time':'CreditCard',
    '/payment-part-time':'Suitcase',
    '/human-efficiency':'DataAnalysis',
    '/cost-split-full-time':'Collection',
    '/cost-split-part-time':'CoffeeCup',
    '/bank-reconciliation':'SetUp',


}

export const useMenuStore = defineStore('menu', () => {
    const menuList = ref<MenuItem[]>([])
    const routesAdded = ref(false)

    // 获取菜单列表
    const getMenus = async () => {
        // 检查是否已有菜单数据
        try {
            if (menuList.value.length === 0) {
                const res = await getMenuList()
                menuList.value = res?.data?.info_list
            }
            routesAdded.value = true
            // 生成动态路由并缓存
            generateDynamicRoutes(menuList.value)
        } catch (error) {
            console.error('获取菜单失败:', error)
            routesAdded.value = true
        }
    }

    // 清空菜单缓存
    const clearMenuCache = () => {
        menuList.value = []
    }

    // 递归生成路由菜单
    const generateMenus = (menus: MenuItem[]): GeneratedMenu[] => {
        return menus.map(menu => ({
            path: menu.url,
            title: menu.name,
            icon: getIconByPath(menu.url),
            children: menu.childs?.length > 0 ? generateMenus(menu.childs) : []
        }))
    }

    // 获取额外的路由配置
    const getExtraRoutes = (url: string): RouteItem | null => {
        // console.log(url);
        
        if (url === '/employeeManage') {
            return {
                path: '/employeeManage/detail/:id?',
                name: 'employeeManageDetail',
                meta: {title: '员工详情'},
                component: () => import('@/views/employeeManage/detail.vue')
            }
        }
        if (url === '/storeManage') {
            return {
                path: '/schedulingManage/detail/:groupId?',
                name: 'schedulingManageDetail',
                meta: {title: '排班详情'},
                component: () => import('@/views/storeManage/schedulingManage/detail.vue')
            }
        }
        return null
    }

// 获取额外的路由配置
    const getExtraRoutes2=(url: string)=>{
        if (url === '/storeManage') {
            return {
                path: '/schedulingManage/PremiumStore/:groupId?',
                name: 'schedulingManagePremiumStore',
                meta: {title: '高级排班'},
                component: () => import('@/views/storeManage/schedulingManage/PremiumStore.vue')
            }
        }
        if (url === '/employeeManage') {
            return {
                path: '/employeeManage/ReOnboarding/:id?',
                name: 'employeeManagepartReOnboarding',
                meta: {title: '重新入职'},
                component: () => import('@/views/employeeManage/ReOnboarding.vue')
            }
        }
        
        return null
    }



    const routesAddedData = () => {
        return routesAdded.value
    }

    // 生成动态路由
    const generateDynamicRoutes = (menus: MenuItem[], parentPath: string = ''): RouteItem[] => {
        const extraRoutes: RouteItem[] = []
        const modules = import.meta.glob('@/views/**/*.vue') as Record<string, () => Promise<any>>

        const routes: RouteItem[] = menus.map(menu => {
            const url = menu.url.startsWith('/') ? menu.url : `/${menu.url}`
            const fullPath = parentPath ? `${parentPath}${url}` : url
            const routeName = parentPath
                ? `${parentPath.replace(/\//g, '.')}.${menu.name}`.replace(/^\./, '')
                : menu.name

            const extraRoute = getExtraRoutes(fullPath)
            
            const extraRoute2=getExtraRoutes2(fullPath)
            if (extraRoute) {
                extraRoutes.push(extraRoute)
            }
            if (extraRoute2) {
                extraRoutes.push(extraRoute2)
            }

            const viewPaths = [
                `/src/views${fullPath}/index.vue`,
                `/src/views${url}/index.vue`
            ]

            let component
            for (const path of viewPaths) {
                if (modules[path]) {
                    component = modules[path]
                    break
                }
            }

            return {
                path: url,
                name: routeName, // 使用生成的唯一名称
                component: component || (() => import('@/views/NotFound.vue')),
                meta: {title: menu.name},
                children: menu.childs?.length > 0
                    ? generateDynamicRoutes(menu.childs, fullPath)
                    : []
            }
        })

        // 如果是顶层调用，添加路由
        if (!parentPath) {
            const allRoutes = [...routes, ...extraRoutes]
            // console.log('Generated routes:', allRoutes)

            allRoutes.forEach(route => {
                try {
                    router.addRoute({
                        path: '/',
                        component: Layout,
                        children: [route]
                    })
                } catch (error) {
                    console.error(`Failed to add route ${route.name}:`, error)
                }
            })
        }

        return routes
    }


    // 根据路径获取图标
    const getIconByPath = (path: string): string => {
        return ICON_MAP[path] || 'Document'
    }

    return {
        menuList,
        getMenus,
        clearMenuCache,
        generateMenus,
        routesAddedData
    }
}, {
    persist: true
})
